<template>
  <a-layout :class="['layout', 'dashboard-layout', device]">
    <a-layout-header class="dashboard-layout-header">
      <main-header />
    </a-layout-header>
    <a-layout-content class="dashboard-layout-content">
      <transition name="page-transition">
        <route-view />
      </transition>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { mixinDevice } from '@/utils/mixin'
import RouteView from './RouteView'
import PageView from './PageView'
import MainHeader from '@/components/MainHeader'
import { mapState, mapActions } from 'vuex'
import { getWsPort } from '@/api/message'
import ws from '@/utils/websocket'

export default {
  name: 'DashboardLayout',
  mixins: [mixinDevice],
  components: {
    RouteView,
    PageView,
    MainHeader
  },

  computed: {
    ...mapState({
      userId: state => state.user.info.id
    })
  },

  mounted () {
    this.getMsgUnread(this.userId)
    // this.getWsPort()
  },

  beforeDestroy () {
    if (this._messageWs) {
      this._messageWs.close()
      this._messageWs = null
    }
  },

  methods: {
    ...mapActions({
      getMsgUnread: 'message/GET_MSG_UNREAD'
    }),

    getWsPort () {
      getWsPort().then(res => {
        const { data: port } = res
        console.log(port)
        this._messageWs = ws(
          {
            onmessage: msgEvent => {
              if (msgEvent.data) {
                const msg = JSON.parse(msgEvent.data)
                this.$store.commit('message/UPDATE_APP_UNREAD', msg)
              }
            }
          },
          { port, url: `/ws/${this.userId}` }
        )
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/components/index.less';

.layout {
  &.dashboard-layout {
    overflow: auto;

    .dashboard-layout-header {
      position: fixed;
      top: 0;
      right: 0;
      z-index: 9;
      width: 100%;
      -webkit-transition: width 0.2s;
      transition: width 0.2s;
    }

    .dashboard-layout-content {
      width: 100%;
      margin: @mos-header-height auto 0;
      padding: 24px;
    }
  }
}
</style>
